﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application;

namespace Cms.Web.Framework.Controls
{
    public class LocalizedLiteral : Control
    {
        private string _boundControlID;
        private string _text;
        private string _translationFile;
        private ITranslatable _view;
        
        public string BoundControlID
        {
            get { return _boundControlID; }
            set { _boundControlID = value; }
        }
        
        public string Text
        {
            get { return _text; }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!(TemplateControl is ITranslatable))
                throw new ApplicationException(
                    "LocalizedLiteral controls can only be used in a page that implements ITranslatable.");

            _view = (ITranslatable)TemplateControl;
            _translationFile = _view.ContextTranslationFile;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string localizationCode;

            // Check ITranslatable.Localization first. This should cover all adminpages.
            if (_view.Localization != null)
                localizationCode = _view.Localization;
            else if (HttpContext.Current.Items["Localization"] is string)
                localizationCode = (string)HttpContext.Current.Items["Localization"];
            else
                localizationCode = "en-US";
            _text = Translator.GetText(_translationFile, ID, localizationCode);
            if (_boundControlID != null)
            {
                Control c = TemplateControl.FindControl(_boundControlID);
                if (c != null)
                {
                    if (c is LinkButton)
                        (c as LinkButton).Text = _text;
                }
            }
            if (!Visible)
                return;
            writer.Write(_text);
        }
    }
}